import http from '@/utils/request.js'

// ========================================
// 用户认证 API (AuthController)
// ========================================

// 用户注册
export const register = (form) => {
  return http.post('/auth/register', {
    Username: form.Username,
    Password: form.Password,
    Email: form.Email,
    Phone: form.Phone
  })
}

// 用户登录
export const login = (form) => {
  return http.post('/auth/login', {
    Username: form.Username,
    Password: form.Password
  })
}

// 刷新访问令牌
export const refreshToken = (refreshToken, forceRefresh = false) => {
  return http.post('/auth/refresh-token', {
    refreshToken,
    forceRefresh
  })
}

// 验证用户信息（忘记密码前验证）
export const validateUserInfo = (form) => {
  return http.post('/auth/validate-user-info', {
    email: form.email,
    phone: form.phone
  })
}

// 忘记密码 - 邮箱和手机号验证
export const forgetPassword = (FormData, forgetPwd) => {
  return http.post('/auth/forget-password', {
    email: FormData.email,
    phone: FormData.phone,
    newPassword: forgetPwd.NewPassword,
    confirmPassword: forgetPwd.ConfirmPassword
  })
}

// 获取当前用户权限
export const getCurrentUserPermissions = () => {
  return http.get('/auth/permissions')
}

// ========================================
// 用户管理 API (UsersController)
// ========================================

// 获取用户列表
export const getUserList = (page = 1, size = 10, search = '') => {
  return http.get('/users', {
    page,
    size,
    search
  })
}

// 获取用户详情
export const getUserDetail = (userId) => {
  return http.get(`/users/${userId}`)
}

// 创建用户
export const createUser = (userData) => {
  return http.post('/users', {
    UserName: userData.UserName,
    Password: userData.Password,
    Email: userData.Email,
    PhoneNumber: userData.PhoneNumber
  })
}

// 更新用户
export const updateUser = (userId, userData) => {
  return http.put(`/users/${userId}`, {
    UserName: userData.UserName,
    Email: userData.Email,
    PhoneNumber: userData.PhoneNumber
  })
}

// 删除用户（软删除）
export const deleteUser = (userId) => {
  return http.delete(`/users/${userId}`)
}

// 修改密码
export const changePassword = (userId, oldPassword, newPassword, confirmPassword) => {
  return http.post(`/users/${userId}/change-password`, {
    OldPassword: oldPassword,
    NewPassword: newPassword,
    ConfirmPassword: confirmPassword
  })
}

// 启用用户
export const enableUser = (userId) => {
  return http.post(`/users/${userId}/enable`)
}

// 禁用用户
export const disableUser = (userId) => {
  return http.post(`/users/${userId}/disable`)
}

// 上传用户头像
export const uploadUserAvatar = (userId, filePath) => {
  return http.upload(`/users/${userId}/avatar`, filePath)
}

// 获取头像文件（匿名访问）
export const getAvatarFile = (fileName) => {
  return http.get(`/users/avatar-file/${fileName}`)
}

// ========================================
// 工具函数
// ========================================

// 保存token到本地存储
export const saveToken = (tokenData) => {
  if (tokenData.accessToken) {
    uni.setStorageSync('token', tokenData.accessToken)
  }
  if (tokenData.refreshToken) {
    uni.setStorageSync('refreshToken', tokenData.refreshToken)
  }
  if (tokenData.user) {
    uni.setStorageSync('userInfo', tokenData.user)
  }
}

// 获取本地存储的token
export const getToken = () => {
  return uni.getStorageSync('token')
}

// 获取本地存储的refreshToken
export const getRefreshToken = () => {
  return uni.getStorageSync('refreshToken')
}

// 获取本地存储的用户信息
export const getUserInfo = () => {
  return uni.getStorageSync('userInfo')
}

// 清除本地存储的认证信息
export const clearAuth = () => {
  uni.removeStorageSync('token')
  uni.removeStorageSync('refreshToken')
  uni.removeStorageSync('userInfo')
}

// 检查是否已登录
export const isLoggedIn = () => {
  const token = getToken()
  return !!token
}

// 自动刷新token
export const autoRefreshToken = async () => {
  try {
    const refreshToken = getRefreshToken()
    if (!refreshToken) {
      throw new Error('No refresh token')
    }
    
    const result = await refreshToken(refreshToken, false)
    if (result.data) {
      saveToken(result.data)
      return result.data.accessToken
    }
  } catch (error) {
    console.error('Token refresh failed:', error)
    clearAuth()
    throw error
  }
}

// 检查token是否过期
export const isTokenExpired = (token) => {
  if (!token) return true
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    return payload.exp < currentTime
  } catch (error) {
    return true
  }
}

// 获取有效的token
export const getValidToken = async () => {
  let token = getToken()
  
  if (!token || isTokenExpired(token)) {
    token = await autoRefreshToken()
  }
  
  return token
}